package net.expectx.common.single.util;

import java.security.MessageDigest;

/**
 * Md5Util
 * @author jianhun
 * @date 2018/5/22
 */
public class Md5Util {
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }


        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }
    private static final String [] HEX_DIGITS = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    public static void main(String[] args) throws Exception {
        System.out.println(Md5Util.md5("expect-x鑫达","UTF-8"));
    }


    public static String md5(String origin, String charsetName) {
        try {
            String resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetName == null || "".equals(charsetName)){
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            }
            else{
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetName)));
            }

            return resultString;
        }catch (Exception e){
            return "";
        }
    }
    public final static String md5(String content) {
        try {
            return md5(content,"UTF-8");
        } catch (Exception e) {
            return null;
        }

    }

}
